﻿using OpenCvSharp;
using Sdcb.PaddleDetection;
using Sdcb.PaddleInference;
using System.IO;

namespace Hr.Orc.Client.Helper
{
    public class SealStamp
    {

        private readonly string modelName = "seal";
        private readonly PaddleDetector detector;
        /// <summary>
        /// 分值
        /// </summary>
        public float Confidence { get; set; }=0.9f;
        public SealStamp()
        {
            PaddleConfig paddleConfig = PaddleConfig.FromModelDir(AppContext.BaseDirectory + $"{modelName}");
            string configYmlPath = Path.Combine(AppContext.BaseDirectory, $"{modelName}\\infer_cfg.yml");
            detector = new PaddleDetector(paddleConfig, configYmlPath);
        }
        public DetectionResult[] CheckSeal(string imagePath)
        {
            Mat src = Cv2.ImRead(imagePath);
            DetectionResult[] r = detector.Run(src);
            return r;
        }


        public bool CheckHasSeal(string imagePath)
        {
            DetectionResult[] r = CheckSeal(imagePath);
            return r.Any(s => s.Confidence > Confidence);
        }

        public bool CheckHasSeal(string imagePath, string outPutDirectory, string fileName)
        {
            try
            {
                if (!Directory.Exists(outPutDirectory))
                {
                    Directory.CreateDirectory(outPutDirectory);
                }
                var savePath = Path.Combine(outPutDirectory, fileName + ".png");
                DetectionResult[] r = CheckSeal(imagePath);
                Mat src = Cv2.ImRead(imagePath);
                bool hasSeal = false;
                foreach (var detection in r)
                {
                    if (detection.Confidence > Confidence)
                    {
                        Scalar scalar = Scalar.RandomColor();
                        Cv2.Rectangle(src, detection.Rect, scalar, 4, LineTypes.Link8, 0);
                        Cv2.PutText(src, detection.LabelName, new OpenCvSharp.Point(detection.Rect.X + detection.Rect.Width / 2, detection.Rect.Y + detection.Rect.Height / 2), HersheyFonts.HersheyComplex, 2D, scalar, 4, LineTypes.Link4, false);
                        hasSeal = true;
                    }
                }
                src.SaveImage(savePath);
                return hasSeal;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public string[] GetLabels()
        {
            var labelList = detector.Config.LabelList;
            return labelList;
        }
    }
}
